<?php
// 创建资源
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$socket) {
    printf("创建 socket 资源失败 \r\n");
    return;
}

// 链接 redis
$state = socket_connect($socket, '127.0.0.1', 6379);
if (!$state) {
    printf("链接 redis 失败 \r\n");
    return;
}

// command set name lqs
$setCommand = sprintf("*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$3\r\nlqs\r\n");
$wRes = socket_write($socket, $setCommand, strlen($setCommand));
if ($wRes == 0) {
    printf("写入失败,%s \r\n", socket_last_error($socket));
}
$buf = socket_read($socket, 1024); // ???? // +ok\r\n
printf("result: %s, size: %d \r\n", trim($buf), strlen($buf));

// command get name
$getCommand = sprintf("*2\r\n$3\r\nGET\r\n$4\r\nname\r\n");
$wRes = socket_write($socket, $getCommand, strlen($getCommand)); // 请求协议
if ($wRes == 0) {
    printf("写入失败,%s \r\n", socket_last_error($socket));
}
$result = socket_read($socket, 1); // 批量回复
switch($result) {
    case '$': // 
        $len = socket_read($socket, 1);
        $buf = socket_read($socket, $len * 3);
        printf("result: %s, size: %d \r\n", trim($buf), strlen($buf));
        break;
    default:
        printf("error");
}
